"""
租房相关视图函数
"""
import json
import os
from io import BytesIO
from uuid import uuid1

# import requests
from django.shortcuts import render

from common.utils import upload_stream_to_qiniu


def home(request):
    """首页"""
    # resp = requests.get(f'https://120.77.222.217/api/houseinfos/')
    return render(request, 'index.html', {})


def to_publish(request):
    """发布页"""
    return render(request, 'publish.html', {})


def publish(request):
    """发布房源"""
    files = request.FILES.getlist('mainphoto')
    for file in files:
        _, ext = os.path.splitext(file.name)
        # 为上传文件生成文件名的方式（上传到七牛云存储的key）：
        # 1. 时间戳 - 有可能产生重复
        # 2. uuid1 - 重复文件无法判定
        # 3. hash摘要 - 计算哈希摘要需要花时间
        filename = uuid1().hex + ext
        file_stream = BytesIO(file.read())
        upload_stream_to_qiniu.delay(file_stream, filename, file.size)
